package com.daocao.hua.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.daocao.hua.R;
import com.daocao.hua.api.callback.OpinionContract;
import com.daocao.hua.api.requestInfo.OpinionRequest;
import com.daocao.hua.util.PreferenceUtils;
import com.daocao.hua.constant.Const;
import com.daocao.hua.model.OpinionModel;
import com.daocao.hua.model.ResponseModel;
import com.daocao.hua.model.UploadImageModel;
import com.daocao.hua.util.ImageUtil;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.CircularProgress;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 建议与意见界面
 * Created by Master.Dong on 16/4/10.
 */
public class OpinionActivity extends BaseActivity implements View.OnClickListener, TextWatcher, OpinionContract.View {

    private int id;
    private CircularProgress loading;
    private EditText content;
    private String imgStr;
    private ImageView[] v = new ImageView[3];
    private String[] photoStr = new String[3];

    //    private List<SpinerAdapterNew.OpinionType> mListType = new ArrayList<SpinerAdapterNew.OpinionType>();  //类型列表
//    //    private TextView mTView;
//    private SpinerAdapterNew mAdapter;
    private int selectType;
    //    private SpinerPopWindow mSpinerPopWindow;
    private TextView okBtn;
    private OpinionRequest api;
    private RadioButton rbOne;
    private RadioButton rbTwo;
    private RadioButton rbThree;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.opinion_activity);
        baseInitView(this, "OpinionActivity", Const.ViewType.ACTIVITY);
        initView();

    }


    private void initView() {
        api = OpinionRequest.create();
        api.attachView(this);
        setTitleText(getResources().getString(R.string.opinion));
        setBackIntent();

        loading = (CircularProgress) findViewById(R.id.progressBar);
        content = (EditText) findViewById(R.id.o_content);
        okBtn = (TextView) findViewById(R.id.ok);
        rbOne = (RadioButton) findViewById(R.id.rb_one);
        rbTwo = (RadioButton) findViewById(R.id.rb_two);
        rbThree = (RadioButton) findViewById(R.id.rb_three);
        okBtn.setOnClickListener(this);
//        mTView = (TextView) findViewById(R.id.tv_value);

//        ((LinearLayout) findViewById(R.id.bt_dropdown)).setOnClickListener(this);
        content.addTextChangedListener(this);

        v[0] = (ImageView) findViewById(R.id.img_1);
        v[1] = (ImageView) findViewById(R.id.img_2);
        v[2] = (ImageView) findViewById(R.id.img_3);
        v[0].setOnClickListener(this);
        v[1].setOnClickListener(this);
        v[2].setOnClickListener(this);

//        okBtn.setBackgroundResource(R.drawable.btn_gray_bg);
        getOpinionType();

    }


//    private void showSpinWindow() {
////        Log.e("", "showSpinWindow");
//        mSpinerPopWindow.setWidth(Util.getDisplayMetrics(this).widthPixels);
//        mSpinerPopWindow.showAsDropDown(mTView);
//    }


    /**
     * 是否显示加载框
     *
     * @param b
     */
    private void showLoading(boolean b) {
        if (loading != null) {
            if (b) {
                okBtn.setEnabled(false);
                loading.setVisibility(View.VISIBLE);
            } else {
                okBtn.setEnabled(true);
                loading.setVisibility(View.GONE);
            }
        }
    }

    private boolean checkInput() {
        if (TextUtils.isEmpty(content.getText().toString().trim())) {
//            ToastUtil.makeText(this, getResources().getString(R.string.content_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ok:
                if (System.currentTimeMillis() - PreferenceUtils.getLong(this, "opinion_time", 0) < 30 * 1000)
                    ToastUtil.makeText(this, getResources().getString(R.string.take_a_break), Toast.LENGTH_SHORT).show();
                else {
                    if (checkInput()) {
                        PreferenceUtils.putLong(getApplicationContext(), "opinion_time", System.currentTimeMillis());
                        showLoading(true);
                        getImage(0);
                    }
                }
                break;
            case R.id.img_1:
                id = 1;
                selectImage();
                break;
            case R.id.img_2:
                id = 2;
                selectImage();
                break;
            case R.id.img_3:
                id = 3;
                selectImage();
                break;

//            case R.id.bt_dropdown:
//                if (mListType.size() > 0)
//                    showSpinWindow();
//                break;
        }
    }

    private void selectImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                "image/*");
        startActivityForResult(intent, 0x1);
    }

    /**
     * 获取类型
     */
    private void getOpinionType() {
        api.getOpinionTypeInfo();
    }


    /**
     * 获取意见或建议
     */
    private void getOpinion() {
        try {
            String str = "";
            if (v[0].getDrawable() != null || v[1].getDrawable() != null || v[2].getDrawable() != null)
                str = Util.stringForArray(photoStr, ',');

            String contentS = "";
            if (!TextUtils.isEmpty(content.getText().toString()))
                contentS = URLEncoder.encode(content.getText().toString(), "utf-8");
            if (rbOne.isChecked()) {
                selectType = 1;
            } else if (rbTwo.isChecked()) {
                selectType = 2;
            } else if (rbThree.isChecked()) {
                selectType = 3;
            }
            api.getOpinionInfo(selectType + "", contentS, str);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private void getImage(int i) {
        try {
            if (i > v.length - 1 || v[0].getDrawable() == null && v[1].getDrawable() == null && v[2].getDrawable() == null) {
                getOpinion();

                //清空图片数组
                for (int j = 0; j < 3; j++) {
                    photoStr[j] = "";
                }
            } else {
                if (v[i].getDrawable() != null) {
                    Bitmap image = ((BitmapDrawable) v[i].getDrawable()).getBitmap();
                    //            RBLog.i("bitmap---", image);
                    imgStr = ImageUtil.Bitmap2StrByBase64(image);
                    //                RBLog.i("str---", imgStr);
                    getUploadImage(i, imgStr);
                } else {
                    photoStr[i] = "";
                    getImage(i + 1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getUploadImage(final int i, String imageStr) {
        api.uploadImg(i, imageStr);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x1 && resultCode == -1) {
            if (data != null) {
                if (id == 1) {
                    if (v[1].getVisibility() == View.GONE) {
                        v[1].setVisibility(View.VISIBLE);
                        Glide.with(this).load(data.getData()).asBitmap().thumbnail(0.4f).into(v[1]);
                    } else if (v[2].getVisibility() == View.GONE) {
                        v[2].setVisibility(View.VISIBLE);
                        Glide.with(this).load(data.getData()).asBitmap().thumbnail(0.4f).into(v[2]);
                    } else {
                        Glide.with(this).load(data.getData()).asBitmap().thumbnail(0.4f).into(v[0]);
                    }
                } else if (id == 2) {
                    Glide.with(this).load(data.getData()).asBitmap().thumbnail(0.4f).into(v[1]);
                } else if (id == 3)
                    Glide.with(this).load(data.getData()).asBitmap().thumbnail(0.4f).into(v[2]);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        api.detachView();
        for (int i = 0; i < v.length; i++) {
            ImageUtil.releaseImageViewResouce(v[i]);
        }

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
//        if (content.getText().toString().isEmpty()) {
//            okBtn.setBackgroundResource(R.drawable.btn_gray_bg);
//        } else {
//            okBtn.setBackgroundResource(R.drawable.btn_d_red_bg);
//        }
    }

    @Override
    public void showError() {
        PreferenceUtils.putLong(getApplicationContext(), "opinion_time", 0);
    }

    @Override
    public void complete() {
        showLoading(false);
    }

    @Override
    public void onRequestStart() {
        showLoading(true);
    }

    @Override
    public void uploadImgSuccess(int i, UploadImageModel model) {
        photoStr[i] = model.getShort_url();
        getImage(i + 1);
    }

    @Override
    public void getOpinionInfoSuccess(ResponseModel model) {
        ToastUtil.makeText(getApplicationContext(), model.getMsg(), Toast.LENGTH_SHORT).show();
        content.setText("");
        v[0].setImageDrawable(null);
        v[1].setImageDrawable(null);
        v[1].setVisibility(View.GONE);
        v[2].setImageDrawable(null);
        v[2].setVisibility(View.GONE);
    }

    @Override
    public void getOpinionTypeInfoSuccess(OpinionModel model) {
        if (model.getData().size() == 3) {
            rbOne.setText(model.getData().get(0).getName());
            rbTwo.setText(model.getData().get(1).getName());
            rbThree.setText(model.getData().get(2).getName());
            rbOne.setChecked(true);
        }
//        for (int i = 0; i < model.getData().size(); i++) {
//            SpinerAdapterNew.OpinionType type = new SpinerAdapterNew.OpinionType();
//            type.setId(model.getData().get(i).getId());
//            type.setName(model.getData().get(i).getName());
//            mListType.add(type);
//
//            if (model.getData().get(i).getSelected() == 1) {
//                selectType = model.getData().get(i).getId();
////                mTView.setText(model.getData().get(i).getName());
//            }
//        }

//        mAdapter = new SpinerAdapterNew(mListType, OpinionActivity.this);
//        mAdapter.refreshData(mListType, 0);

        //初始化PopWindow
//        mSpinerPopWindow = new SpinerPopWindow(OpinionActivity.this);
//        mSpinerPopWindow.setAdatper(mAdapter);
//        mSpinerPopWindow.setItemListener(OpinionActivity.this);


    }
}
